package com.yuneec.fly.presenters;

import android.content.SharedPreferences;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.yuneec.fly.DroneApplication;
import com.yuneec.fly.fragments.BindModelFragment;

import java.util.List;

/**
 * Created by gjw on 2016/12/22.
 */

public abstract class AbstractBindPresenter extends BasePresenter implements View.OnClickListener {
    public final static String SP_TAG = "BIND_INFO.-.";
    public int mChecked = -1;
    public String bind;
    public SharedPreferences mShare = DroneApplication.getApplication().getSharedPreferences(SP_TAG, 0);

    public void start(String bind) {
        this.bind = bind;
    }

    public void stop() {
    }

    public abstract List getDatas();

    public abstract boolean removeIndex(int index);

    public abstract String getCurrentBind();

    public final static int STATE_NONE = 0;
    public final static int STATE_SCAN = 1;
    public final static int STATE_BIND = 2;
    public final static int STATE_RESET = 3;
    public final static int STATE_OPEN = 4;
    private volatile int state;

    public boolean checkState(int tState) {
        if (state != STATE_NONE) {
            synchronized (this) {
                if (state != STATE_NONE) {
                    return false;
                }
            }
        }
        state = tState;
        return true;
    }

    public void resetState() {
        this.state = STATE_NONE;
    }

    public abstract String getName(int position);

    public abstract int getSize();

    private void setCheck(RecyclerView view, int checked, boolean check) {
        if (checked != -1) {
            BindModelFragment.ListItem item = (BindModelFragment.ListItem) view.findViewHolderForAdapterPosition(mChecked);
            if (item != null) {
                item.tv.setChecked(check);
            }
        }
    }

    @Override
    public void onClick(View v) {
        RecyclerView parent = (RecyclerView) v.getParent();
        setCheck(parent, mChecked, false);
        Object tag = v.getTag();
        if (tag != null) {
            mChecked = (int) tag;
            setCheck(parent, mChecked, true);
        }
    }
}
